package pers.cz.encrypt;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.DES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

/**
 * 加解密工具，敏感信息加密存储
 * @program: PostGirl-panent
 * @description: EncryptUtil
 * @author: Cheng Zhi
 * @create: 2021-05-26 14:41
 **/
public class DesUtil {

    private static Logger logger = LoggerFactory.getLogger(DesUtil.class);
    // 生成密钥，并转为字符串，可以储存起来，解密时可直接使用
    private static byte[] key1 = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue()).getEncoded();
    // 偏移
    private static byte[] key2 = "Csbt34.Ydhl12s".getBytes();
    private static String secretKey = "MQuUKYbZ8kNDc2J0MzQuWWRobDEycw=="; // 暂时写死，后续需要保存动态公钥到数据库
/*    private static String secretKey;
    static {
        byte[] key3 = new byte[key1.length + key2.length];
        System.arraycopy(key1, 0, key3, 0, key1.length);
        System.arraycopy(key2, 0, key3, key1.length, key2.length);
        secretKey = new BASE64Encoder().encodeBuffer(key3);
    }*/

    /**
     * 加密
     * @param info
     * @return
     */
    public static String encrypt(String info) {
        byte[] key = new byte[0];
        try {
            key = new BASE64Decoder().decodeBuffer(secretKey);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        DES des = SecureUtil.des(key);
        String encrypt = des.encryptHex(info);
        return encrypt;
    }

    /**
     * 解密
     * @param encrypt
     * @return
     */
    public static String decode(String encrypt) {
        byte[] key = new byte[0];
        try {
            key = new BASE64Decoder().decodeBuffer(secretKey);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        DES des = SecureUtil.des(key);
        return des.decryptStr(encrypt);
    }

    public static void main(String[] args) {
        String encrypt = encrypt("1hblsqT!");
        System.out.println("密文:" + encrypt);

        String decrypt = decode("e10adc3949ba59abbe56e057f20f883e");
        System.out.println("明文:" + decrypt);

    }

}
